package com.zhima.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : 芝麻
 * @date : 2023-08-05 18:17
 **/
public class FileUtil {
    public static List<String> readFile(BufferedReader br) throws IOException {
        try {
            List<String> ans = new ArrayList<>();
            String line;
            while ((line = br.readLine()) != null) {
                ans.add(line);
            }
            return ans;
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

    public static List<String> readFile(String filePath) throws IOException {
        return readFile(new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8)));
    }

    public static List<String> readFile(File file) throws IOException {
        return readFile(new BufferedReader(new FileReader(file, StandardCharsets.UTF_8)));
    }

    public static boolean deleteFile(String filePath) {
        return new File(filePath).delete();
    }

    public static void deleteFileIfExists(String filePath) {
        new File(filePath).delete();
    }

    public static boolean exists(String filePath) {
        return new File(filePath).exists();
    }

    public static void ensureDirExist(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
